<?php

// +----------------------------------------------------------------------
// | 悟空信息技术有限公司
// +----------------------------------------------------------------------
// | Copyright (c)2016 http://www.wkidt.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: wkidt team LSQ <admin@wkidt.com> 2017/5/15 21:35
// +----------------------------------------------------------------------
// | Readme: 字典类
// +----------------------------------------------------------------------

namespace app\system\logic;

use app\system\model\Dictionary as DictionaryModel;
use think\Cache;

class Dictionary
{

    protected static $instance = null;

    /**
     * 获取一个实例
     *
     * @return static
     */
    public static function instance()
    {
        if (is_null(static::$instance)) {
            static::$instance = new static();
        }
        return static::$instance;
    }

    /**
     * 禁止new
     *
     * Dictionary constructor.
     */
    private function __construct()
    {

    }

    /**
     * 获取字典文本
     *
     * @param $key
     * @param null $value
     * @param null $default
     * @return null|string
     */
    public function get($key, $value = null, $default = null)
    {
        $data = $this->getData();
        if (!isset($data[$key])) {
            return $default;
        } elseif (is_null($value)) {
            return $data[$key];
        } else {
            return isset($data[$key][$value]) ? $data[$key][$value] : '';
        }
    }

    /**
     * 获取字典值
     *
     * @param $key
     * @return array
     */
    public function getKeys($key)
    {
        $data = $this->getData();
        if (array_key_exists($key, $data) && is_array($data[$key])) {
            return array_keys($data[$key]);
        } else {
            return [];
        }
    }

    /**
     * 获取字典数据
     *
     * @return mixed
     */
    public function getData()
    {
        $data = Cache::get('dictionary_map');
        if (empty($data)) {
            $list = DictionaryModel::instance()->alias('d')
                ->join('__SYS_DICTIONARY_VALUE__ dv', 'd.id=dv.dictionary_id')
                ->field(['d.id', 'd.key', 'd.name', 'dv.value', 'dv.text'])
                ->select();

            foreach ($list as $key => $val) {
                $data[$val['key']][$val['value']] = $val['text'];
            }
            Cache::set('dictionary_map', $data);
        }
        return $data;
    }
}
